package org.jetlinks.pro.things.impl.converter;

import lombok.AllArgsConstructor;
import org.jetlinks.core.message.ThingMessage;
import org.jetlinks.pro.things.ThingMessageConverter;
import org.jetlinks.pro.things.utils.ThingsUtils;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.function.Supplier;


@AllArgsConstructor
public class TemplateThingMessageConverter implements ThingMessageConverter {

    private final Supplier<ThingMessage> template;

    private final ThingMessageConverter converter;

    @Override
    public Mono<ThingMessage> convert(Map<String, Object> context, ThingMessage message) {
        //使用消息作为上下文,并返回新的消息
        Map<String, Object> newContext = ThingsUtils.messageToContextMap(message);
        newContext.putAll(context);
        return converter
            .convert(newContext, template.get())
            .doOnNext(msg -> {
                //转换器没有设置thingId,则认为使用当前物
                if (StringUtils.isEmpty(msg.getThingId())) {
                    msg.thingId(message.getThingType(), message.getThingId());
                }
            });
    }
}
